package net.pulseproject.commons.test;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public final class Util {
	
	private Util() {
		// utility classes should not be instantiated
	}
	
	public static Map<String, Object> createMap(final Object... keyValues) {
		if(keyValues.length == 0) {
			return Collections.emptyMap();
		}
		
		if(keyValues.length % 2 != 0) {
			throw new IllegalArgumentException("keyValues.length = " + keyValues.length);
		}
		
		final Map<String, Object> map = new HashMap<String, Object>();
		final int n = (keyValues.length + 1) / 2;
		for (int i = 0; i < n; i++) {
			final String key = (String) keyValues[i * 2];
			final Object val = keyValues[i * 2 + 1];
			map.put(key, val);
		}
		return map;
	}
	

	public static String join(final Collection<?> items) {
		return Util.join(items, ", ");
	}
	
	public static String join(final Collection<?> items, final String separator) {
		final StringBuilder sb = new StringBuilder();
		
		boolean first = true;
		for (final Object item : items) {
			if(first == false) {
				sb.append(separator);
			}
			sb.append(String.valueOf(item));
			first = false;
		}
		
		return sb.toString();
	}

	public static String join(final Map<?, ?> items) {
		return Util.join(items, "=", ", ");
	}
	
	public static String join(final Map<?, ?> items, final String entrySeparator, final String itemSeparator) {
		final StringBuilder sb = new StringBuilder();
		
		boolean first = true;
		for (final Entry<?, ?> entry : items.entrySet()) {
			if(first == false) {
				sb.append(itemSeparator);
			}
			sb.append(String.valueOf(entry.getKey()));
			sb.append(entrySeparator);
			sb.append(String.valueOf(entry.getValue()));
			first = false;
		}
		
		return sb.toString();
	}
	
}
